package cn.king.user.service.impl;

import cn.king.basic.exception.BusinessException;
import cn.king.basic.jwt.JwtUtils;
import cn.king.basic.jwt.LoginData;
import cn.king.basic.jwt.RsaUtils;
import cn.king.basic.util.AjaxResult;
import cn.king.basic.util.HttpUtil;
import cn.king.basic.util.Md5Utils;
import cn.king.basic.util.StrUtils;
import cn.king.sys.domain.Menu;
import cn.king.sys.service.IMenuService;
import cn.king.user.constant.WxConstants;
import cn.king.user.domain.Logininfo;
import cn.king.user.domain.User;
import cn.king.user.domain.Wxuser;
import cn.king.user.dto.LoginDto;
import cn.king.user.mapper.LogininfoMapper;
import cn.king.user.mapper.UserMapper;
import cn.king.user.mapper.WxuserMapper;
import cn.king.user.service.ILogininfoService;
import cn.king.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private IMenuService menuService;

    /**
     * 账号登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();
        //空值校验
        if(StringUtils.isEmpty(account)){
            throw new BusinessException("账号不能为空!!!");
        }
        if(StringUtils.isEmpty(checkPass)){
            throw new BusinessException("密码不能为空!!!");
        }
        //账号校验
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);//登录信息
        if(logininfo==null){
            throw new BusinessException("账号或密码错误!!!");
        }
        //校验密码：加密加盐
        //前端输入的密码进行加密加盐
        String inputPwd = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        if(!inputPwd.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误!!!");
        }
        //校验 - 是否被禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被禁用，请联系管理员!!!");
        }
        return loginSuccessJwtHandler(logininfo);
    }

    /**
     * 微信登录
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求：需要code，appid，secret；返回token，openid
        //准备第二个请求的地址
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",map.get("code"));
        //使用HttpUtils发送微信登录请求：第二个请求，返回json格式的String
        String jsonStr = HttpUtil.httpGet(url);
        //通过fastJson将json格式的字符串转成json对象，为了获取token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //通过openid查t_wxuser表
        Wxuser wxuser = wxuserMapper.getByOpenid(openid);

        //现在有两种情况：查到了和没查到
        //第一种情况：查到了：以前扫过码，免密登录，返回true，token和logininfo对象
        if (wxuser != null){
            //根据user_id有可能查到对象
            User user = userMapper.getOne(wxuser.getUserId());
            if (user != null){ //绑定了user
                Logininfo logininfo = logininfoMapper.getOne(user.getLogininfoId());
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setObj(resultMap);
            }
        }
        //第二种情况：没查到：第一次扫码，把token和openid传给前端，到绑定页面进行绑定
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);
    }

    /**
     * 微信绑定
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验-空值
        if (StringUtils.isEmpty(phone)){
            throw new BusinessException("电话号码不能为空！");
        }
        if (StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("验证码不能为空！");
        }
        //2.校验-手机验证码：是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if (obj == null){
            throw new BusinessException("验证码已过期，请重新获取！");
        }
        if (!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("验证码错误！");
        }
        //3.准备第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换WxUser对象
        Wxuser wxuser = jsonStr2WxUser(jsonStr);
        //6.创建User对象和Logininfo对象【phone】 - 难度
        //以前通过手机注册过，但是没有绑定微信
        User user = userMapper.getByPhone(phone);
        if (user == null){
            //手机号码没有绑定过
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        wxuser.setUserId(user.getId()); //微信用户绑定userid
        wxuserMapper.add(wxuser);
        //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.getOne(user.getLogininfoId());
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setObj(resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5 = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }

    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>(); //传递给前端的
        LoginData loginData = new LoginData(); //使用jwt加密的
        //设置logininfo
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        logininfo.setPhone(null);
        logininfo.setEmail(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);

        //设置menus，permissions - 管理员
        if (logininfo.getType() == 0){
            //设置permissions
            List<String> permissions = logininfoMapper.getPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //设置Menus
            List<Menu> menus = logininfoMapper.getMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //设置jwt Token - 加密 - loginData
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader()
                    .getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
